package com.itcam.imitate;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author : Cammy.Wu
 * Description : 破解机器人的秘密零件（字段操作）
 */

public class Story02 {
    /*
        魔法书第二章写着："机器人胸口有隐藏的能源核心（private字段），
        名字叫 energyCore，你可以修改它！"
     */

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
        // 通过反射创建一个机器人的灵魂
        Class<?> robotClazz = Class.forName("com.itcam.imitate.Robot");
        Field energyField = robotClazz.getDeclaredField("energyCore");

        energyField.setAccessible(true);

        Object robotInstance = robotClazz.getDeclaredConstructor().newInstance();

        // 查看原始能量值
        int energy = (int) energyField.get(robotInstance);
        System.out.println("当前能量：" + energy);

        // 注入超级energy
        energyField.set(robotInstance,90000);
        System.out.println("新能量：" + energyField.get(robotInstance));
    }
}
